package edu.nyu.hps.architecture;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

/**
 * This class acts as a thread on the server which communicates with the applet
 * 
 * @author hiralrajani
 * 
 */
public class AppletThread extends Thread {
	int turn = 1;
	private Socket socket = null;
	Player cat, mouse;

	public AppletThread(Socket socket, Player mouse, Player cat) {
		super("Interface");
		this.cat = cat;
		this.mouse = mouse;
		this.socket = socket;
		System.out.println("New Applet thread created!");
	}

	/**
	 * Listens to the server and writes to the applet
	 */
	public void run() {
		try {
			turn = 1;
//			System.out.println("Started again!");
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			//Printing initial locations of CAT and mouse to Interface
			out.println("INITIAL:" + cat.x + "," + cat.y + ":" + mouse.x + "," + mouse.y);
	
			//Retrieving cat name and mouse name string
			while (cat.name == null || mouse.name == null) {
				System.out.print("");
			}
			out.println("NAME:" + cat.name +":" +mouse.name);
//			System.out.println("Catname = " + cat.name);
//			System.out.println("Mousename = " + mouse.name);

			//Passing on the moves information of the players
			while (true) {
				
				//cats
				if (cat.pastMoves.containsKey(turn)
						&& mouse.pastMoves.containsKey(turn)) {
					String catout = "";
					ArrayList<Point> catMove = cat.pastMoves.get(turn);
					for (Point p : catMove) {
						catout += p.toString() + ":";
					}
					out.println(catout.substring(0, catout.length() - 1));
//					System.out.println("TURN:" + turn + "CAT"
//							+ catout.substring(0, catout.length() - 1));

					out.println(mouse.pastMoves.get(turn).get(0).toString());
//					System.out.println("TURN:" + turn + "MOUSE"
//							+ mouse.pastMoves.get(turn).get(0).toString());

					turn++;
				}
				
				//mouse
				if(turn>=mouse.totalMoves+1 && cat.caught && mouse.caught){
//					System.out.println("TURN when caught " + turn);
					out.println("STATUS: CAUGHT");
					break;
				}
				
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			System.out.println("Could not get I/O from the server thread!");
		}
	}

}
